﻿using Microsoft.EntityFrameworkCore;
using TraceBility.Interstructrue;

namespace TraceBility.Host.Write.Extension
{
    /// <summary>
    /// 拓展方法  静态类  静态方法  this关键字 
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //swagger
            builder.Services.AddSwaggerGen();

            //注册EFCore上下文  开发环境下启用SQL日志记录
            builder.Services.AddDBContextAccessor<EFDBContext>(builder.Configuration.GetConnectionString("DefaultConnection"), builder.Environment.IsDevelopment());
            //中介者模式 
            builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());

            return builder;
        }

        /// <summary>
        /// 注册EFCore上下文
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString">链接字符串</param>
        /// <param name="enableSqlLog">是否启用sql日志</param>
        /// <returns></returns>
        public static IServiceCollection AddDBContextAccessor<T>(this IServiceCollection services, string connectionString, bool enableSqlLog) where T : DbContext
        {
            return services.AddDbContext<EFDBContext>(p =>
            {
                p.UseSqlServer(connectionString, action =>
                {
                    //配置EFCore的重试策略
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10, //最大重试次数
                        maxRetryDelay: TimeSpan.FromSeconds(60),//每次重试间隔时间 最大延迟 
                        errorNumbersToAdd: null); //添加需要重试的错误代码，null表示使用默认的错误代码
                })
                .EnableSensitiveDataLogging(); //启用敏感数据日志记录，便于调试，但在生产环境中应谨慎使用以避免泄露敏感信息

                if (enableSqlLog)
                {
                    //配置日志记录
                    p.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddFilter(
                        category: DbLoggerCategory.Database.Name, //类别
                        level: LogLevel.Information//日志级别
                        ).AddConsole())); //控制台日志
                }
            });
        }



    }
}
